<template>
  <div class='fullscreen'>
    <div  v-if="beCalling" class='fullscreen allBack'>
      <cover-view class='callImage clearfix'>
        <cover-image  class='img' :src="talkInfo.doctorImg"></cover-image>
        <cover-view>
          <cover-view style="height: 67rpx;line-height: 67rpx;font-size:48rpx;color: #fff;">{{talkInfo.doctor_name}}</cover-view>
          <cover-view  style="height: 37rpx;line-height: 37rpxfont-size:26rpx;color: #fff;margin-top: 10rpx;">请求视频聊天…</cover-view>
        </cover-view>
      </cover-view>
      <cover-view class='close clearfix'>
        <cover-view class='closeItem'>
          <cover-image class="calling-close" v-if="imgUrl" :src="imgUrl + 'netcall-reject.png'"  @click="rejectCallHandler"></cover-image>
          <cover-view>拒绝</cover-view>
        </cover-view>
        <cover-view class='closeItem'>
          <cover-image class="calling-close" src="/static/images/acceptCallHandler.png"  @click="acceptCallHandler"></cover-image>
          <cover-view>接听</cover-view>
        </cover-view>
      </cover-view>
      <audio src="/static/avchat_ring.mp3" id="myAudio" autoplay loop='true'></audio>
      <!-- <div class='becalling-button-group'>
        <div class='reject-button button' @click='rejectCallHandler'>拒绝</div>
        <div class='accept-button button' @click='acceptCallHandler'>接听</div>
      </div> -->
    </div>
    <!-- 只能医生发视频给患者 -->
    <div v-else class='fullscreen'>
      <div class='fullscreen'>
        <div class='video-wrapper'>
          <block v-for="(item, index) in userlist" :key='index'>
            <!-- 显示发视频的 -->
            <yuyin-pusher
              v-if="item.uid === loginUser.uid"
              :url="item.url"
              :key="item.uid"
              id="yunxin-pusher"
              :enable-camera="enableCamera"
              :muted="muted"
              beauty="true"
              :config="selfPosition"
              bindpushfailed="onPusherFailed"
            >
            </yuyin-pusher>
            <!-- 显示接受视频的 -->
            <yuyin-player
              v-if="item.uid !== loginUser.uid"
              :key="item.uid"
              :uid="item.uid"
              :url="item.url"
              :id="'yunxinplayer-' + item.uid"
              :config="otherPosition"
              bindpullfailed="onPullFailed"
              ></yuyin-player>
              <!-- 消息通知 -->
              <cover-view class='msgTips clearfix'>
                <cover-image class='img fl' src="/static/images/icon_switch_text.png" @click='backChat'></cover-image>
                <cover-image v-if='!enableCamera && imgUrl' class="itemImg1 fl" :src="imgUrl + 'video2.png'"  :data-mode="1" @click="switchMeetingModeHandler">关闭摄像头</cover-image>
                <cover-image v-if='enableCamera && imgUrl' class="itemImg2 fl" :src="imgUrl + 'video1.png'"  :data-mode="1" @click="switchMeetingModeHandler">关闭摄像头</cover-image>
                <cover-image class="itemImgHead fl" v-if="imgUrl" :src="imgUrl + 'changeVideo.png'" @click="switchCameraHandler">切摄像头</cover-image>
                <!-- <cover-view class='unread'>{{unreadLenght}}</cover-view> -->
              </cover-view>
              <cover-view class='control-wrapper'>
                <!-- 时间显示 -->
                <cover-view class='netcall-time-text'>{{duration}}</cover-view>
                <!-- 视频的控制显示 -->
                <cover-view class='videobtm'>
                  <cover-view v-if='muted' class='item' >
                    <cover-image class="itemImg"  v-if="imgUrl" :src="imgUrl + 'netcall-micro-close.png'" data-mode="2" @click="switchMeetingModeHandler"></cover-image>
                    <cover-view>静音</cover-view>
                  </cover-view>
                  <cover-view class='item' v-if='!muted'>
                    <cover-image  class="itemImg"  v-if="imgUrl" :src="imgUrl + 'netcall-micro.png'" data-mode="2"  @click="switchMeetingModeHandler"></cover-image>
                  <cover-view>静音</cover-view>
                  </cover-view>
                  <cover-view class='item'>
                    <cover-image class="itemImg"  v-if="imgUrl" :src="imgUrl + 'netcall-reject.png'"  @click="hangupHandler"></cover-image>
                    <cover-view>挂断</cover-view>
                  </cover-view>
                  <cover-view class='item' v-if='handsfree'>
                    <cover-image class="itemImg"  v-if="imgUrl" :src="imgUrl + 'mianti.png'" data-mode="2" @click="switchhandsfree('ear')"></cover-image>
                    <cover-view>免提</cover-view>
                  </cover-view>
                  <cover-view class='item' v-if='!handsfree'>
                    <cover-image  v-if="imgUrl"  class="itemImg" :src="imgUrl + 'mianti_open.png'" data-mode="2"  @click="switchhandsfree('speaker')"></cover-image>
                    <cover-view>免提</cover-view>
                  </cover-view>
                </cover-view>
              </cover-view>
          </block>
        </div>
      </div>
      <i-toast id="toast" />
      <i-message id="message" />
    </div>
  </div>
</template>

<script>
  const app = getApp()
  let store = app.store
  let needRePublish = false
  let needRePlay = true
  let callingBackToLast = false
  import { mapState } from 'vuex'
  import yuyinPusher from '@/components/yuyinPusher.vue'
  import yuyinPlayer from '@/components/yuyinPlayer.vue'
  import Bus from '@/utils/bus.js'
  import nim from '@/utils/nim'
	const { $Toast, $Message } = require('../../../../../static/iview/base/index')
  import * as types from '@/store/types'
  export default {
    data () {
      return {
        onTheCall: false, //正在通话中标记
        isCalling: false,// 主叫中
        beCalling: false, // 被叫中
        callingPosition: {}, // 呼叫中的位置
        enableCamera: true, // 开启摄像头标记
        handsfree: false, // 是否免提
        muted: false, // 静音标记
        userlist: [], // 所有用户列表
        loginUser: {}, // {uid,account,cid}
        infoOfBeCalled: {}, // 被叫时传递过来的：主叫信息 {caller,cid,type}
        netcallTime: 0, // 通话时长
        duration: '', // 格式化后的时间
        selfPosition: {}, // 自己的位置
        otherPosition: {}, // 对端的位置大小
        callTypeIconKind: 'video', // 当前的通话类型，音频通话为audio，视频通话为video
        // 音视频流重连标记
        streamNeedReconnect: false,
        streamStoped: false,
        joinObject: {}, // 加入的数据
        callTimerId: null,
        netcallTimeTimer: null,
        unreadLenght:  0,
        titleHeight: 0,
        showMsgArr: [],
				imgUrl: '',
        doctorInfo: {},
        innerAudioContext: null
      }
    },
    computed: {
      ...mapState([
        'talkInfo', 'ifVideoing'
      ])
    },
    components: {
      yuyinPusher, yuyinPlayer
    },
    onShow () {
      // this.unreadLenght = 0
      this.duration = ''
      this.showMsgArr = []
      this.$store.commit(this.$types.if_VIDEOING, true)
    },
    onLoad (options) {
      let that = this
			that.imgUrl = that.$imgUrl
      that.innerAudioContext = wx.createInnerAudioContext()
      that.innerAudioContext.autoplay = true
      that.innerAudioContext.loop = true
      that.innerAudioContext.src = 'https://ks3-cn-beijing.ksyun.com/wxapp/wdrm/image/patient/avchat_ring.mp3'
      that.innerAudioContext.play()
      app.globalData.isPushBeCallPage = false // 记录是否打开视频页面
      that.queryDetails()
      let menuButtonObject = mpvue.getMenuButtonBoundingClientRect()
      mpvue.getSystemInfo({
        success: res => {
          let statusBarHeight = res.statusBarHeight
          that.titleHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight)*2
        }
      })
      // wx.setNavigationBarTitle({
      //   title: `与${that.videoInfo.regular_name}的视频聊天`,
      // })
      that.handsfree = false
      if (options.beCalling) {
        // 被呼叫
        that.beCalling = true,
        that.infoOfBeCalled = {
          caller: options.caller,
          cid: options.cid,
          type: options.type
        }
      } else {
        // that.createdTime()
      }
      that._initialPosition()
      that.listenNetcallEvent()
    },
    mounted(){
      let that = this
      wx.onAppHide((res) =>{
        if (that.onTheCall || that.isCalling) {
          console.log('退出小程序 关闭视频')
          that.hangupHandler()
          // wx.navigateBack(1)
        }
      })
    },
    onUnload() {
      // 有问题？
      if (this.onTheCall || this.isCalling) {
        this.hangupHandler()
      }
      this.$store.commit(this.$types.if_VIDEOING, false)
      this.innerAudioContext.stop()
    },
    methods: {
      // 查看详情
      queryDetails () {
        let that = this
        clearInterval(that.timer)
        that.showBtm = false
        that.$api.appointmentDetail({apt_id: that.talkInfo.aptId},({'showLoading': false})).then((res) => {
          that.doctorInfo = res.data[0]
          let obj = that.talkInfo
          obj.status = res.data[0].status,
          obj.doctor_name = res.data[0].doctor_name,
          obj.netease_id = res.data[0].netease_id,
          obj.sessionId = 'p2p-' + res.data[0].netease_id,
          obj.doctorImg = res.data[0].doctor_image,
          obj.diagnose_time = res.data[0].apt_end_time
					obj.apt_id = that.talkInfo.aptId
          // let obj = {
          //   status: res.data[0].status,
          //   category: res.data[0].category,
          //   regular_id: res.data[0].regular_id,
          //   doctor_name: res.data[0].doctor_name,
          //   netease_id: res.data[0].netease_id,
          //   sessionId: 'p2p-' + res.data[0].netease_id,
          //   doctorImg: res.data[0].doctor_image,
          //   diagnose_time: res.data[0].apt_end_time
          // }
          that.$store.commit(that.$types.TALK_INFO, Object.assign({}, obj))
          console.log(that.talkInfo, 'info----------')
        })
      },
      switchhandsfree (status) {
        this.handsfree = !this.handsfree
        Bus.$emit('changeSound', status)
      },
      // 返回聊天
      backChat () {
        console.log(this.doctorInfo, 'doctorInfo')
        let obj = {
          status: this.doctorInfo.status,
          category: this.doctorInfo.category,
          regular_id: this.doctorInfo.regular_id,
          doctor_name: this.doctorInfo.doctor_name,
          netease_id: this.doctorInfo.netease_id,
          sessionId: 'p2p-' + this.doctorInfo.netease_id,
          doctorImg: this.doctorInfo.doctor_image,
          diagnose_time: this.doctorInfo.apt_end_time,
          apt_id: this.talkInfo.apt_id
        }
        this.$store.commit(this.$types.TALK_INFO, obj)
        mpvue.navigateTo(
          {
            url: `/pages/chat/child/graphicChat/main`
          }
        )
        // this.unreadLenght = 0
        // 更新会话对象
        store.dispatch({
          type: 'CurrentChatTo_Change',
          payload: this.talkInfo.sessionId
        })
        // 告知服务器，标记会话已读
        nim.resetSessionUnread(this.talkInfo.sessionId)
      },
      /**
       * 接听通话
       */
      acceptCallHandler (e) {
        let self = this
        self.innerAudioContext.stop()
        // 显示通信画面
        app.globalData.netcall.response({
          caller: this.infoOfBeCalled.caller,
          accepted: true,
          type: this.infoOfBeCalled.type,
          cid: this.infoOfBeCalled.cid
        })
          .then(() => {
            // 开启音视频逻辑
            app.globalData.netcall.startRtc({ mode: 0 })
              .then((data) => {
                self._clearCallTimer()
                self.beCalling = false
                self.isCalling = false
                self.loginUser = data
                self.streamNeedReconnect = true
                self.livePusherContext = mpvue.createLivePusherContext()
              })
          })
          .catch((error) => {
            console.error(error)
            const duration = 2000
            this.$utils.showToast('text', `接听失败，请重试，${duration / 1000}秒后返回`, { duration })
            this.hangupHandlerAfter(0)
          })
      },
      // 拒绝通话
      rejectCallHandler(e) {
        this.innerAudioContext.stop()
        this._clearCallTimer()
        app.globalData.netcall.response({
          caller: this.infoOfBeCalled.caller,
          accepted: false,
          type: this.infoOfBeCalled.type,
          cid: this.infoOfBeCalled.cid
        })
          .then(() => {
            this._resetData()
            this.hangupHandlerAfter(0)
          })
          .catch((error) => {
            console.error(error)
          })
      },
      /**
       * 开关摄像头、麦克风回调
       * 0音视频，1纯音频，2纯视频，3静默
       */
      switchMeetingModeHandler(e) {
        let mode = e.currentTarget.dataset.mode
        let enableCamera = this.enableCamera
        let muted = this.muted
        if (mode == 1) { // 单击了关闭摄像头 => 纯音频
          enableCamera = !enableCamera
          if (enableCamera) { // 摄像头开启 => 关闭摄像头
            if (muted) {
              mode = 2
            } else {
              mode = 0
            }
          } else { // 摄像头关闭 => 开启摄像头
            if (muted) {
              mode = 3
            } else {
              mode = 1
            }
          }

          if (enableCamera) {
            this.$utils.showToast('text', '摄像头已打开')
          } else {
            this.$utils.showToast('text', '摄像头已关闭')
          }
        } else if (mode == 2) { // 单击了关闭麦克风 => 纯视频
          muted = !muted
          if (muted) { // 静音：false => true
            if (enableCamera) {
              mode = 2
            } else {
              mode = 3
            }
          } else { // true => false
            if (enableCamera) {
              mode = 0
            } else {
              mode = 1
            }
          }
          if (muted) {
            this.$utils.showToast('text', '麦克风已关闭')
          } else {
            this.$utils.showToast('text', '麦克风已打开')
          }
        }
        // 切换本地状态
        this.enableCamera = enableCamera
        this.muted = muted
        if (mode == 1) {
          this.stopStream(0).then(() => {
            this.reconnectStreamAfter(100)
          })
        }
        app.globalData.netcall.switchMode(mode)
          .then(() => {
          })
          .catch((err) => {
            console.error(err)
          })
      },
      // 切换摄像头回调
      switchCameraHandler() {
        this.livePusherContext.switchCamera()
      },
      onPullFailed() {
        needRePlay = true
      },
      // 初始化主动呼叫病患
      // createdTime () {
      //   // 只能医生主动呼叫病患
      //   app.globalData.isPushBeCallPage = false
      //   mpvue.setKeepScreenOn({
      //     keepScreenOn: true
      //   })
      //   this.isCalling = true,
      //   this.callingPosition = {
      //     x: 0,
      //     y: 0,
      //     width: app.globalData.videoContainerSize.width,
      //     height: app.globalData.videoContainerSize.height + 50
      //   }
      //   let newObject = {
      //     category: this.talkInfo.category + '',
      //     regular_id: this.talkInfo.regular_id + '',
      //     aptId: this.talkInfo.apt_id
      //   }
      //   nim.callVideo({
      //       // type: this.callTypeIconKind === 'video' ? 2 : 1, // 通话类型：1音频，2视频
      //       type: 2,
      //       callee: this.talkInfo.netease_id, // 被叫
      //       custom: JSON.stringify(newObject),
      //       forceKeepCalling: true, // 持续呼叫
      //       error:function (error) {
      //         const duration = 2000
      //         this.$utils.showToast('text', `呼叫失败，请重试，${duration / 1000}秒后返回`, { duration })
      //         this.hangupHandlerAfter(duration)
      //       }
      //     })
      //     clearTimeout(this.callTimerId)
      //     this.callTimerId = setTimeout(() => { // ok
      //       const duration = 3000
      //       this.$utils.showToast('text', `无人接听，视频将在${duration/1000}秒后关闭`, { duration })
      //       this.hangupHandlerAfter(duration)
      //     }, 100 * 1000)
      // },
      // 清除呼叫定时器
      _clearCallTimer () {
        if (this.callTimerId) {
          clearTimeout(this.callTimerId)
          this.callTimerId = null
        }
      },
      onPusherFailed() {
        needRePublish = true
      },
      onPullFailed() {
        needRePlay = true
      },
      // 视频相对显示位置
      _initialPosition() {
        let containerSize = app.globalData.videoContainerSize // 外部容器大小
        let selfPosition = {
          x: containerSize.width - 100 - 30,
          y: 60,
          width: 100,
          height: 150
        }
        let otherPosition = {
          x: 0,
          y: 0,
          width: containerSize.width,
          height: containerSize.height
        }
        this.selfPosition = selfPosition
        this.otherPosition = otherPosition
      },
      hangupHandlerAfter(duration = 0) {
        clearTimeout(this.hangupTimer)
        this.hangupTimer = setTimeout(() => { // ok
          this.hangupHandler()
        }, duration)
      },
      /**
       * 格式化需要时间
       */
      _formateDuration(time) {
        let hour = parseInt(time / 3600)
        let minute = parseInt((time - hour * 3600) / 60)
        let second = time % 60
        return {
          hour: this.$utils.formatNumber(hour),
          minute: this.$utils.formatNumber(minute),
          second: this.$utils.formatNumber(second)
        }
      },
      // 对开启视频中间环节处理
      listenNetcallEvent() {
        let self = this
        app.globalData.emitter.on('syncDone', (data) => {
          // self._mergeUserList(this.userlist, data.userlist)
          let userlist = Object.assign([], data.userlist)
          if (userlist.length == 1) {
            userlist.push({})
            userlist.reverse()
          }
          // console.error(userlist)
          if (self.userlist.length == 2) {
            self.streamNeedReconnect = true
            self.userlist = []
            setTimeout(() => {
              self.onTheCall = true, // 正在通话中标记
              self.userlist = userlist
            }, 70)
            this.$utils.showToast('text', '媒体流重新建立中，请稍后')
            self.reconnectStreamAfter(100)
            return
          }
          self.onTheCall = true, // 正在通话中标记
          self.userlist = userlist,
          self.streamNeedReconnect = true
          self.reconnectStreamAfter()
          // 设置通话定时计时器
          self._clearCallTimer()
          if (!self.netcallTimeTimer) {
            self.netcallTimeTimer = setInterval(() => {
              let { hour, minute, second } = self._formateDuration(self.netcallTime + 1)
              self.netcallTime = self.netcallTime + 1
              self.duration = `${hour}:${minute}:${second}`
            }, 1000)
          }
        })
        app.globalData.emitter.on('callAccepted', (data) => {
          clearTimeout(self.hangupTimer)
          // 开启音视频逻辑
          app.globalData.netcall.startRtc({ mode: 0 })
            .then((data) => {
              self.livePusherContext = mpvue.createLivePusherContext()
              self.loginUser = data
              self.isCalling = false
              self.streamNeedReconnect = true
            })
        })
        app.globalData.emitter.on('callRejected', (data) => { // 有用
          clearTimeout(this.hangupTimer)
          self.onTheCall = false
          const duration = 2000
          // this.$utils.showToast('text', `对方拒绝，${duration / 1000}秒后返回`, { duration })
          this.hangupHandlerAfter(duration)
        })
        app.globalData.emitter.on('clientLeave', (data) => {
        })
        app.globalData.emitter.on('clientJoin', (data) => {
          self._personJoin(data)
          // self.$api.videoStatus({apt_id: self.talkInfo.apt_id, status_type: '0', channel_Id: data.cid}, ({'showLoading': true})).then(function (res) {
          // })
        })
        app.globalData.emitter.on('beCalling', (data) => {
          if (this.onTheCall || this.isCalling || this.infoOfBeCalled.cid != data.cid) {
            // 如果通话中，则拒绝
            app.globalData.netcall.response({
              accepted: false,
              caller: data.caller,
              type: data.type,
              cid: data.cid
            })
            return
          }
          this.infoOfBeCalled = data
        })
        app.globalData.emitter.on('hangup', (data) => {
          // 接通过程
          if (data.cid != this.loginUser.cid && this.onTheCall) {
            console.warn('接通过程,非本通通话，抛弃')
            return
          }
          // 被叫过程
          if (this.beCalling && this.infoOfBeCalled.cid != data.cid) {
            console.warn('被叫过程,非本通通话，抛弃')
            return
          }
          // 主叫过程
          if (this.isCalling && data.account != this.pageTitle) {
            console.warn('主叫过程,非本通通话，抛弃')
            return
          }
          this._clearCallTimer()

          const duration = 2000
          this.$utils.showToast('text', `对方已经挂断`, { duration })
          this.hangupHandlerAfter(0)
        })
        app.globalData.emitter.on('control', (data) => {
          this.controlHandler(data)
        })
        // 信令准备重连
        app.globalData.emitter.on('willreconnect', () => {
          this.stopStream()
        })
      },
      reconnectStreamAfter (duration = 0) {
        clearTimeout(this.reconnectStreamTimer)
        this.reconnectStreamTimer = setTimeout(() => {
          this.reconnectStream()
        }, duration)
      },
      controlHandler(_data) {
        let self = this
        switch (_data.command) {
          // 主动请求从音频切换到视频
          case app.globalData.netcall.NETCALL_CONTROL_COMMAND_SWITCH_AUDIO_TO_VIDEO:
            mpvue.showModal({
              title: '切换通话模式',
              content: '对方请求从音频切换到音视频',
              confirmText: '允许',
              cancelText: '拒绝',
              success: function (res) {
                let { confirm, cancel } = res
                if (confirm) { // 单击了允许
                  self.agreeSwitchAudioToVideo()
                }
                if (cancel) { // 单击了取消
                  self.rejectSwitchAudioToVideo()
                }
              }
            })
            break
          // 对方同意从音频切换到视频
          case app.globalData.netcall.NETCALL_CONTROL_COMMAND_SWITCH_AUDIO_TO_VIDEO_AGREE:
            // 切换音频到视频
            this.switchToVideoCall()
            break
          // 对方拒绝从音频切换到视频
          case app.globalData.netcall.NETCALL_CONTROL_COMMAND_SWITCH_AUDIO_TO_VIDEO_REJECT:
            showToast('text', '对方拒绝音频切换到音视频')
            break
          // 从视频切换到音频
          case app.globalData.netcall.NETCALL_CONTROL_COMMAND_SWITCH_VIDEO_TO_AUDIO:
            // 切换视频到音频
            self.switchToVoiceCall()
            break
        }
      },
      // 开始推流
      reconnectStream () {
        if (this.streamNeedReconnect) {
          this.$utils.showToast('text', '建议携带耳机接诊')
          clearTimeout(this.stopStreamTimer)
          this.livePusherContext.start({
            success: () => {
              this.streamStoped = false
            },
            complete: () => {
              if (!this.livePlayerMap) {
                this.livePlayerMap = {}
              }
              this.userlist.map(user => {
                const uid = `${user.uid}`
                if (user.uid != this.loginUser.uid) {
                  if (!this.livePlayerMap[uid]) {
                    this.livePlayerMap[uid] = mpvue.createLivePlayerContext(`yunxinplayer-${user.uid}`, this)
                  }
                  console.error(this.livePlayerMap[uid])
                  // this.$utils.showToast('text', '开始重连拉流')
                  this.livePlayerMap[uid].play()
                }
              })
            }
          })
        }
      },
      // 停止推流
      stopStream (duration = 1000) {
        if (this.stopStreamTimer) {
          clearTimeout(this.stopStreamTimer)
        }
        if (this.streamStoped) {
          return Promise.resolve()
        }
        return new Promise((resolve, reject) => {
          this.stopStreamTimer = setTimeout(() => {
            if (!this.livePusherContext) {
              return
            }
            if (!this.livePlayerMap) {
              this.livePlayerMap = {}
            }
            this.userlist.map(user => {
              const uid = `${user.uid}`
              if (user.uid != this.loginUser.uid) {
                if (!this.livePlayerMap[uid]) {
                  this.livePlayerMap[uid] = mpvue.createLivePlayerContext(`yunxinplayer-${user.uid}`, this)
                }
                this.livePlayerMap[uid].stop()
              }
            })
            this.livePusherContext.stop({
              complete: () => {
                this.streamStoped = true
                resolve()
              }
            })
          }, duration)
        })
      },
      _personJoin(data) {
        let userlist = Object.assign([], this.userlist)
        let uids = userlist.map(user => user.uid) || []
        if (uids.includes(data.uid) === false) {
          // 非自己
          if (this.loginUser.uid !== data.uid) {
            this.$set(this.userlist, 0, data)
          }
        }
      },
      /**
       * 挂断通话
       */
      hangupHandler(notBack = false) {
        // promise不接着往下走？ 把原方法替换掉了
        if (app.globalData.netcall) {
          app.globalData.netcall.hangup()
          console.log(app.globalData, 'app.globalData')
        }
        this.innerAudioContext.stop()
        // 停止推拉流
        this._resetData()
        this.$utils.showToast('text', '通话结束')
        setTimeout(() => {
          this.stopStream(0)
          if (notBack !== true) {
            this._judgeNavigateBack(0)
          }
          this._clearCallTimer()
          this._clearNetcallTimeTimer()
          this._unBindNetcallEvent()
          clearTimeout(app.globalData.videoCallTimer)
          app.globalData.videoCallTimer = setTimeout(() => {
            app.globalData.waitingUseVideoCall = false
          }, 2000)
          app.globalData.waitingUseVideoCall = true
        }, 2000);
      },
      _unBindNetcallEvent() {
        app.globalData.emitter.eventReset()
      },
      // 清除通话计时定时器
      _clearNetcallTimeTimer() {
        this.netcallTime = 0
        if (this.netcallTimeTimer) {
          clearTimeout(this.netcallTimeTimer)
          this.netcallTimeTimer = null
        }
      },
      // 校验是否需要返回上一层，
      _judgeNavigateBack(delayTime = 0) {
        let pages = getCurrentPages()
        let currentPage = pages[pages.length - 1]
        let currentPage2 = pages[pages.length - 2]
        if (currentPage.route.includes('videoCall') === true) {
          setTimeout(() => {
            mpvue.navigateBack(1)
          }, delayTime)
        } else if (currentPage2.route.includes('videoCall') === true) {
          mpvue.navigateBack({
            delta: 2
          })
        }
        // else if (!this.ifVideoing) {
        //   mpvue.navigateBack(1)
        // }
      },
      _resetData () {
        clearTimeout(this.hangupTimer)
        clearTimeout(this.callTimerId)
        this._resetStreamState()
        this.beCalling = false
        this.isCalling = false,
        this.onTheCall = false, // 通话中的标记复位
        this.userlist = []
      },
      _resetStreamState () {
        clearTimeout(this.stopStreamTimer)
        this.streamNeedReconnect = false,
        this.streamStoped = false
      }
    },
    watch: {
      // ifVideoing: function (newValue, oldValue) {
      //   if (!newValue) {
      //     let pages = getCurrentPages()
      //     let currentPage = pages[pages.length - 1]
      //     if (currentPage.route.includes('videoCall') !== true || currentPage.route.includes('graphicChat') !== true) {
      //       // this.hangupHandler()
      //     }
      //   }
      // }
    }
  }
</script>

<style scoped lang='less'>
  .callImage {
    width: 100%;
    padding-top: 400rpx;
    text-align: center;
    .img {
      display: inline-block;
      width: 200rpx;
      height: 200rpx;
      border-radius: 100%;
      margin-bottom: 36rpx;
    }
  }
  .callhead {
    background: #0088FF;
    text-align: center;
    color: #fff;
    .unread {
      font-size: 24rpx;
    }
  }
  .msgTips {
    color: red;
    position: absolute;
    left: 40rpx;
    top: 50rpx;
    margin-top: 60rpx;
    .img {
      width: 42rpx;
      height: 47rpx;
      padding: 20rpx;
      margin-right:30rpx;
    }
    .itemImgHead {
      width: 47rpx;
      height: 42rpx;
      margin-right:30rpx;
      padding: 20rpx;
    }
    .itemImg1 {
      width: 49rpx;
      height: 49rpx;
      display: inline-block;
      margin-right:30rpx;
      padding: 20rpx;
    }
    .itemImg2 {
      width: 41rpx;
      height: 48rpx;
      display: inline-block;
      margin-right:30rpx;
      padding: 20rpx;
    }
    .unread {
      width: 33rpx;
      height: 33rpx;
      background: #FF5959;
      color: #fff;
      text-align: center;
      line-height: 33rpx;
      font-size: 24rpx;
      border-radius: 100%;
      position: absolute;
      left: 48rpx;
      top: 0rpx;
    }
  }
  .container {
    width: 100%;
    height: 100%;
  }
  /* 被叫 */
  .becalling-wrapper {
    position: relative;
    width:100%;
    height:100%;
    background-color:#777;
    color:#fff;
    font-size:40rpx;
  }
  .becalling-wrapper .becalling-text {
    position: absolute;
    top:400rpx;
    left:50%;
    margin-left:-220rpx;
  }
  .becalling-wrapper .becalling-button-group {
    position: absolute;
    width:100%;
    box-sizing:border-box;
    bottom: 100rpx;
    padding: 0 40rpx;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .becalling-button-group .button {
    width:220rpx;
    height:80rpx;
    border-radius:10rpx;
    justify-content:center;
    display:flex;
    align-items:center;
    font-size:33rpx;
    color:#000;
  }
  .becalling-button-group .reject-button {
    background-color:#f00;
  }
  .becalling-button-group .accept-button {
    background-color:rgb(26, 155, 252);
  }
  .allBack {
    width: 100%;
    height: 100%;
    background: #000;
  }
  .calling-coverview {
    width:100%;
    height:100rpx;
    background-color:#ccc;
    color:#fff;
    font-size:40rpx;
    text-align:center;
    line-height:100rpx;
  }
  .close {
    padding: 0 140rpx;
    position: absolute;
    left: 0;
    bottom: 36rpx;
    text-align: center;
    color: #fff;
    font-size: 28rpx;
    justify-content: space-between;
    .closeItem {
      display: inline-block;
    }
    .closeItem:nth-child(1) {
      margin-right: 230rpx;
    }
  }
  .calling-close {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 19rpx;
  }
  /* 视频容器 */
  .video-wrapper {
    width: 100%;
    height: 100%;
    padding-bottom: 100rpx;
    box-sizing: border-box;
    position: relative;
    background-color: #000;
  }
  .calling-voerview {
    background-color:#ccc;
    color:#fff;
    height: 160rpx;
    font-size: 40rpx;
    text-align: center;
    line-height: 160rpx;
  }
  .control-wrapper {
    z-index: 9999!important;
    width: 100%;
    box-sizing: border-box;
    position: absolute;
    bottom: 0;
  }
  .control-wrapper {
    position: absolute;
    bottom: 36rpx;
    left:0;
    display: flex;
    width: 100%;
    box-sizing: border-box;
    flex-direction: column;
    justify-content: space-between;
    padding: 0 74rpx;
    height: 270rpx;
  }
  .netcall-time-text {
    width:100%;
    height: 40rpx;
    line-height: 40rpx;
    color:#fff;
    font-size:28rpx;
    text-align:center;
    margin-bottom: 42rpx;
  }
  .videobtm {
    flex: 1;
    width: 100%;
    display: flex;
  }
  .videobtm .item {
    flex: 1;
    text-align: center;
    color: #fff;
    .itemImg {
      width: 120rpx;
      height: 120rpx;
      display: inline-block;
      margin-bottom: 19rpx;
    }
  }
  .videoHead {
    height: 300rpx;
    width: 200rpx;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100rpx;
    margin-top: -150rpx;
    text-align: center;
     .img {
       width: 200rpx;
       height: 200rpx;
       margin-bottom: 33rpx;
     }
     .videoName {
       height:67rpx;
       font-size:48rpx;
       font-family:PingFangSC;
       font-weight:500;
       color:#fff;
       line-height:67rpx;
       display: inline-block;
     }
  }
</style>
